using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Domain;
using ErrorCode;
using Infrastructure;
using Microsoft.EntityFrameworkCore;
using RabbitTraceability.Api.Applications.Command;
using RabbitTraceability.Api.Dtos.Response;

namespace RabbitTraceability.Api.Applications.CommandHandler
{
    /// <summary>
    /// 查询图片信息命令处理器
    /// </summary>
    public class QueryImageInfoCommandHandler
    {
        private readonly IRepository<ImageInfo> _imageRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="imageRepository">图片信息仓储</param>
        /// <param name="mapper">对象映射器</param>
        public QueryImageInfoCommandHandler(IRepository<ImageInfo> imageRepository, IMapper mapper)
        {
            _imageRepository = imageRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理查询图片信息命令
        /// </summary>
        /// <param name="command">查询命令</param>
        /// <returns>查询结果</returns>
        public async Task<ApiResult<List<ImageInfoDto>>> Handle(QueryImageInfoCommand command)
        {
            try
            {
                // 构建查询
                var query = _imageRepository.GetAll().Where(x=>x.IsDeleted==false);

                // 根据图片分类筛选
                if (!string.IsNullOrWhiteSpace(command.ImageCategory))
                {
                    query = query.Where(x => x.ImageCategory == command.ImageCategory);
                }

                // 根据生产批次筛选
                if (!string.IsNullOrWhiteSpace(command.ProductionBatch))
                {
                    query = query.Where(x => x.ProductionBatch == command.ProductionBatch);
                }

                // 获取数据并按创建时间降序排序
                var imageInfos = await query
                    .OrderByDescending(x => x.CreatedTime)
                    .ToListAsync();

                // 映射为DTO
                var imageInfoDtos = _mapper.Map<List<ImageInfoDto>>(imageInfos);

                return new ApiResult<List<ImageInfoDto>>(ResultCode.成功, "查询成功", imageInfoDtos);
            }
            catch (Exception ex)
            {
                return new ApiResult<List<ImageInfoDto>>(ResultCode.服务器错误, ex.Message);
            }
        }
    }
} 